from flask import Blueprint, render_template, request
from .user_manager import UserManager

user_bp = Blueprint('user', __name__)

# 实例化 UserManager
user_manager = UserManager()

@user_bp.route('/UserRestList', methods=['GET', 'POST'])
def UserRestListPage():
    username = request.args.get("username", "")  # 获取用户名
    restaurants = user_manager.get_restaurants()
    if restaurants:
        return render_template('UserRestList.html', username=username, result=restaurants, messages="done")
    else:
        return render_template('UserRestList.html', username=username, messages="none")


@user_bp.route('/Menu', methods=['GET', 'POST'])
def menu():
    username = request.args.get("username", "")  # 获取用户名
    if request.method == 'POST':
        action = request.form.get("action")
        restaurant = request.form.get("restaurant", "")

        if action == "进入本店":
            dishes = user_manager.get_dishes_by_restaurant(restaurant)
            if dishes:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, result=dishes, messages="done")
            else:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, messages="none")

        elif action == "特色菜":
            specialty_dishes = user_manager.get_specialty_dishes(restaurant)
            if specialty_dishes:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, result=specialty_dishes, messages="done")
            else:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, messages="none")

        elif action == "按销量排序":
            sorted_dishes = user_manager.get_dishes_sorted_by_sales(restaurant)
            if sorted_dishes:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, result=sorted_dishes, messages="done")
            else:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, messages="none")

        elif action == "按价格排序":
            sorted_dishes = user_manager.get_dishes_sorted_by_price(restaurant)
            if sorted_dishes:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, result=sorted_dishes, messages="done")
            else:
                return render_template('Menu.html', username=username, RESTAURANT=restaurant, messages="none")

    return render_template('Menu.html', username=username, messages="none")


@user_bp.route('/myOrder', methods=['GET', 'POST'])
def shoppingCartPage():
    username = request.args.get("username", "")  # 获取用户名
    cart_items = user_manager.get_shopping_cart()
    if cart_items:
        return render_template('myOrder.html', username=username, result=cart_items, messages="done")
    else:
        return render_template('myOrder.html', username=username, messages="none")